package com.zhou.utis.interceptors;

import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import com.zhou.utis.threadLocal.ThreadLocalUtil;
import com.zhou.utis.dto.LoginDto;
import com.zhou.utis.tokend.TokenException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * 这是拦截器
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    /**
     * 注入redis
     */
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 拦截器
     *
     * @param request  接收
     * @param response 释放
     * @param handler  头部
     * @return 对比token是否正确的结果
     * @throws Exception 抛出自定义异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头上的token
        String token = request.getHeader("Authorizationuser");
        //判空，如果token为空就返回token异常
        if (!StringUtils.hasText(token)) {
            throw new TokenException();
        }
        //获取存在redis上的key是token的数据
        String user = (String) redisTemplate.opsForValue().get("token"+token);
        log.info("{}",user);
        //判空，如果数据为空就返回token异常
        if (StringUtils.isEmpty(user)) {
            throw new TokenException();
        }
        //解析，把字符串转换为相对应的对象
        LoginDto us = JSON.parseObject(user, LoginDto.class);
        log.info("{}",us);
        //判空
        if (us == null) {
            throw new TokenException();
        }
        //将token里面存的数据set到工具类里面
        ThreadLocalUtil.setId(us.getAccountId());
        //使用者在操作时一段时间没有操作就刷新token
        redisTemplate.opsForValue().set("token"+token, JSON.toJSONString(us), 30, TimeUnit.MINUTES);
        return true;

    }
}
